package com.copa.module.cart.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.copa.domain.ResponseDto;
import com.copa.module.cart.domain.dto.CartListDto;
import com.copa.module.cart.domain.entity.CartEntity;
import com.copa.module.cart.domain.vo.CartAddVo;
import com.copa.module.cart.domain.vo.CartUpdateVo;
import com.copa.module.cart.mapper.CartDao;
import com.copa.module.cart.service.CartService;
import com.copa.module.user.manage.UserRoleManage;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author copa
 * @createDate 2021-01-18 15:19
 * @function
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartDao cartDao;

    @Autowired
    private UserRoleManage userRoleManage;

    @Override
    public ResponseDto<List<CartListDto>> list(String openId) {
        Long userId = userRoleManage.getUserByOpenId(openId).getData().getId();
        List<CartListDto> cartListDtos = cartDao.listByUserId(userId);

        if (ObjectUtil.isNotNull(cartListDtos) && ObjectUtil.length(cartListDtos) > 0) {
            // 检查商品是否售卖
            List<CartListDto> cartNoForSaleListDtos = cartDao.listNotSaleByUserId(userId);
            if (ObjectUtil.isNotNull(cartNoForSaleListDtos) && ObjectUtil.length(cartNoForSaleListDtos) > 0) {
                List<Long> deleteCartIds = Lists.newArrayList();
                cartNoForSaleListDtos.forEach(cartNoForSaleListDto -> {
                    deleteCartIds.add(cartNoForSaleListDto.getId());
                });
                cartDao.deleteByIds(deleteCartIds, userId);
                cartListDtos.removeAll(cartNoForSaleListDtos);
            }
            cartListDtos.forEach(cart -> {
                // 处理规格
                List<String> spus = Lists.newArrayList();
                String[] split = cart.getProductName().split(",");
                for (String s : split) {
                    spus.add(s.substring(s.indexOf(":") + 1));
                }
                cart.setProductName(String.join("  ", spus));
            });
            return ResponseDto.success(cartListDtos);
        }
        return ResponseDto.errorMsg("购物车没有东西哦~请添加一些吧~");
    }

    @Override
    @Async
    @Transactional(rollbackFor = Exception.class)
    public ResponseDto<String> put(String openId, CartUpdateVo cartUpdateVo) {
        Long userId = userRoleManage.getUserByOpenId(openId).getData().getId();
        CartEntity cart = new CartEntity();
        BeanUtils.copyProperties(cartUpdateVo, cart);
        cart.setUserId(userId);
        int update = cartDao.updateById(cart);
        if (update > 0) {
            return ResponseDto.success("更改成功");
        }
        return ResponseDto.errorMsg("系统繁忙，请稍后再试！");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseDto<String> delete(String openId, Long cartId) {
        Long userId = userRoleManage.getUserByOpenId(openId).getData().getId();
        CartEntity cart = new CartEntity();
        cart.setIsDelete(1)
                .setUserId(userId)
                .setId(cartId);
        int update = cartDao.updateById(cart);
        if (update > 0) {
            return ResponseDto.success("删除购物车成功！");
        }
        return ResponseDto.errorMsg("系统繁忙，请稍后再试！");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseDto<String> post(String openId, CartAddVo cartAddVo) {
        Long userId = userRoleManage.getUserByOpenId(openId).getData().getId();
        CartEntity cart = null;

        // 查询是否有该记录
//        if (cartAddVo.getId() != null) {
//            cart = cartDao.findByCartIdAndUserId(cartAddVo.getId(), userId);
//        }
        cart = cartDao.findOneCart(cartAddVo, userId);

        // 如果有该记录，则修改
        if (cart != null) {
            cart.setNum(cartAddVo.getNum());
            int update = cartDao.updateById(cart);
            if (update > 0) {
                return ResponseDto.success("添加到购物车成功！");
            }
            return ResponseDto.errorMsg("系统繁忙，请稍后再试！");
        }

        // 如果没该记录，则添加
        cart = new CartEntity();
        BeanUtils.copyProperties(cartAddVo, cart);
        cart.setUserId(userId);
        int insert = cartDao.insert(cart);
        if (insert > 0) {
            return ResponseDto.success("添加到购物车成功！");
        }
        return ResponseDto.errorMsg("系统繁忙，请稍后再试！");
    }

    @Override
    public ResponseDto<String> deleteList(Long userId, List<Long> cartId) {
        int update = cartDao.deleteByIds(cartId, userId);
        if (update > 0) {
            return ResponseDto.success("删除购物车成功！");
        }
        return ResponseDto.errorMsg("系统繁忙，请稍后再试！");
    }

    @Override
    public List<CartEntity> findList(Long userId, List<Long> cartIds) {
        return cartDao.findList(userId, cartIds);
    }
}
